package com.yzw.listeners;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.listener.ReadListener;
import com.yzw.controller.OmsBcReceivableModel;
import com.yzw.dao.entity.OmsBcReceivableEntity;
import com.yzw.service.OmsBcReceivableService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author yw
 * @date 2023/12/26
 * DemoDataListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进入
 */
public class ExcelDataListener implements ReadListener<OmsBcReceivableModel> {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    /**
     *
     */
    private static final int BATCH_COUNT = 1000;
    /**
     * 缓存的数据
     */
    private List<OmsBcReceivableEntity> cachedDataList = new ArrayList<>();
    /**
     *
     */
    private OmsBcReceivableService omsBcReceivableService;


    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        // 插入过程中异常处理
        logger.info("导入数据异常，content:{},异常信息:msg:{}", context, exception.getMessage());
        // 不抛异常正常处理，抛异常则后续停止
        throw new Exception("插入数据异常");
    }

    @Override
    public void invokeHead(Map<Integer, CellData> headMap, AnalysisContext context) {

    }

    @Override
    public void invoke(OmsBcReceivableModel model, AnalysisContext context) {
        // 读取数据
        logger.info("读取数据id：{}", model.getId());
        OmsBcReceivableEntity entity = covert2Entity(model);
        cachedDataList.add(entity);
        if(cachedDataList.size() >= BATCH_COUNT){
            saveData();
        }

    }

    private void saveData() {
        logger.info("{}条数据，开始持久化数据库", cachedDataList.size());
        omsBcReceivableService.batchSaveInit(cachedDataList);
        cachedDataList.clear();
        logger.info("内存集合数据清理，大小size:{}", cachedDataList.size());
    }

    private OmsBcReceivableEntity covert2Entity(OmsBcReceivableModel model) {
        OmsBcReceivableEntity entity = new OmsBcReceivableEntity();
        entity.setId(Long.valueOf(model.getId()));
        String createDateStr = model.getCreateDate();
        Date createDate = DateUtil.parse(createDateStr, DatePattern.NORM_DATE_PATTERN).toJdkDate();
        entity.setCreateDate(createDate);
        String updateDateStr = model.getUpdateDate();
        Date updateDate = DateUtil.parse(updateDateStr, DatePattern.NORM_DATE_PATTERN).toJdkDate();
        entity.setUpdateDate(updateDate);
        entity.setVersion(Long.valueOf(model.getVersion()));
        entity.setOrganizationCode(model.getOrganizationCode());
        entity.setSourceId(Long.valueOf(model.getSourceId()));
        entity.setSourceType(model.getSourceType());
        entity.setApportionIndex(model.getApportionIndex());
        entity.setWaybillId(Long.valueOf(model.getWaybillId()));

        // String planPushDayStr = model.getPlanPushDay();
        //Date planPushDay = DateUtil.parse(planPushDayStr, DatePattern.NORM_DATE_PATTERN).toJdkDate();
        entity.setPlanPushDay(model.getPlanPushDay());
        entity.setInnerPartCode(model.getInnerPartCode());
        entity.setCurrentPrice(Long.valueOf(model.getCurrentPrice()));
        entity.setCurrentQuantity(Long.valueOf(model.getCurrentQuantity()));
        entity.setApportionType(model.getApportionType());
        entity.setChannelOrderId(model.getChannelOrderId());
        entity.setPushStatus(1);
        return entity;
    }

    public ExcelDataListener(OmsBcReceivableService omsBcReceivableService){
        // 本身listener未被sprig管理，只能外部带入
        this.omsBcReceivableService = omsBcReceivableService;
    }

    @Override
    public void extra(CellExtra extra, AnalysisContext context) {

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 所有数据读完执行
        saveData();
        logger.info("所有数据解析完成");
        logger.info("importExcel结束时间：end：{}", System.currentTimeMillis());
    }

    @Override
    public boolean hasNext(AnalysisContext context) {
        // 踩坑点  默认是false，则不会读取excel中数据
        return true;
    }

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();

        list.add(1);
        System.out.println(list.size());
        list.clear();
        System.out.println(list.size());
        list.add(2);
        System.out.println(list.size());
    }
}
